package com.xiao.handler.security;

import com.alibaba.fastjson.JSON;
import com.xiao.domain.ResponseResult;
import com.xiao.enums.AppHttpCodeEnum;
import com.xiao.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 认证失败处理器
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        e.printStackTrace();// 打印异常信息
        // InsufficientAuthenticationException
        // BadCredentialsException

        ResponseResult result=null;

        if (e instanceof BadCredentialsException){ // 坏的凭据异常
            result=ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(),e.getMessage());
        }else if (e instanceof InsufficientAuthenticationException){// 身份验证不足异常 一般是缺少 token
            result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);

        }else {
            result=ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR,"认证或授权失败");
        }
        // 包装成 Json 后响应给前端
        WebUtils.renderString(response, JSON.toJSONString(result));

    }
}